package net.huashitong.Project.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.core.filter.Paging;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.utils.NumberUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import jodd.util.StringUtil;
import net.huashitong.Project.dao.NewProjectsDao;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.util.MessageUtil;
import net.huashitong.log.service.ProjectsLogService;
import net.huashitong.node.dao.NodeNewschedulesDao;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.node.utile.DateUtil;
import net.huashitong.oversee.databean.PlanStartScheduleDto;
import net.huashitong.oversee.entity.GradePoint;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.filter.GradePointFilter;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.GradePointService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.entity.Message;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.user.service.MessageService;
import net.huashitong.utils.BeanSetGetUtil;
import net.huashitong.utils.CompareUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static net.huashitong.Project.util.TimeDataDealWithUtil.kexuejishu;
import static net.huashitong.utils.UtilsTools.removalRepeatArr;

@Service
public class NewProjectsService extends StringPKService<NewProjects> {
    @Autowired
    private MessageUtil mu;
    @Autowired
    private NewProjectsDao dao;
    @Autowired
    private NodeNewschedulesDao nodeNewschedulesDao;
    @Lazy
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private SysTableService tableService;
    @Autowired
    private MessageService ms;
    @Autowired
    private BnpUserService bnpUserService;
    @Autowired
    @Lazy
    private SupervisionTaskService supervisionTaskService;
    @Autowired
    @Lazy
    private GradePointService gradePointService;
    @Autowired
    private ProjectUserChangeService changeService;
    @Autowired
    private ProjectsLogService projectsLogService;

    @Override
    protected BaseDao<NewProjects, String> getDao() {
        return dao;
    }

    @Override
    protected void beforeSave(NewProjects obj) {
        obj.setSysId(tableService.updateMaxSysId("t_bnp_new_project", null));
    }

    public void update(NewProjects projects) {
        this.onPreUpdate(projects);
        this.beforeUpdate(projects);
        dao.update(projects);
        this.afterUpdate(projects);
    }

    public void update(NewProjects projects, String ip, BnpUser user) {
        //存储到项目更改日志里面
        projectsLogService.saveLog(projects, ip, user);
        this.onPreUpdate(projects);
        this.beforeUpdate(projects);
        dao.update(projects);
        this.afterUpdate(projects);
    }

    public List<NewProjects> queryByfilter(NewProjectsFilter filter) {
        return dao.queryByfilter(filter);
    }

    public List<NewProjects> getProjectInfo(NewProjectsFilter filter) {
        if (filter.getCurrentPage() == null || filter.getCurrentPage() == -1) {
            filter.setCurrentPage(1);
        }
        Paging p = new Paging();
        p.setSortCol("sysId");
        p.setSortVal("desc");
        p.setCurrentPage(Integer.valueOf(filter.getCurrentPage()));
        filter.setPaging(p);
        return dao.getProjectInfo(filter);
    }


    public List<NewProjects> getProjectInfoPage(NewProjectsFilter filter) {

        return dao.getProjectInfo(filter);
    }

    /**
     * 审核通过
     *
     * @param filter
     */
    public void initPassProject(NewProjectsFilter filter) {
        boolean startFlag = nodeNewschedulesDao.queryStartFlag(filter.getSysId());
        List<NodeNewschedules> startSmallNodes = new ArrayList<>();
        if (!startFlag) {
//            //没有进行中的节点
//            //攻坚办审核通过的话给前置节点为"#"的大节点以其底下的第一个小节点状态设置为开始。
//            List<NodeNewschedules> nodeNewschedules = nodeNewschedulesDao.getFirstNode1(filter.getSysId());
            //最前面的节点开启（bug）(开启流程过程中最前面的节点)
            List<NodeNewschedules> startNodes = nodeNewschedulesDao.getFirstNode2(filter.getSysId());
            //获取所有节点
            List<NodeNewschedules> list = nodeNewschedulesDao.getNodeByProjectId(filter.getSysId());
            Map<String, NodeNewschedules> openMap = dealWithNodesMapByType(list, "open");
            Map<String, NodeNewschedules> closeMap = dealWithNodesMapByType(list, "close");
//                Map<String, NodeNewschedules> allMap = dealWithNodesMapByType(list, "all");
//                Map<String, String> resMap = new HashMap<>();
            updateStartNode(startNodes, closeMap, openMap);
        }
        //没有进行中的节点
        //攻坚办审核通过的话给前置节点为"#"的大节点以其底下的第一个小节点状态设置为开始。
        List<NodeNewschedules> nodeNewschedules = nodeNewschedulesDao.getFirstNode1(filter.getSysId());
        //有前置节点为"#"的大节点
        if (nodeNewschedules.size() > 0) {
            for (NodeNewschedules nodeNewschedule : nodeNewschedules) {
                NodeNewschedules smallNode = nodeNewschedulesDao.getNode4(nodeNewschedule.getNodeId(), nodeNewschedule.getProjectId());
                smallNode.setStatus("1");
                smallNode.setPlanBeginDate(DateUtil.getDate());
                startSmallNodes.add(smallNode);
                nodeNewschedulesService.update(smallNode);
                nodeNewschedule.setStatus("1");
                nodeNewschedule.setPlanBeginDate(DateUtil.getDate());
            }
            nodeNewschedulesService.batchUpdate(nodeNewschedules);
        }
        //发送节点开启短信
        sendStartMsg(startSmallNodes);
    }

    /**
     * 发送节点开启短信
     *
     * @param nodeLists
     */
    public void sendStartMsg(List<NodeNewschedules> nodeLists) {
        for (NodeNewschedules nodeNewschedules : nodeLists) {
            NewProjects np = getById(nodeNewschedules.getProjectId());
            Map<String, Object> ma = mu.taskMessage(nodeNewschedules.getOperatorUser(), nodeNewschedules.getOperatorPhone(), "《" + np.getName() + "》", nodeNewschedules.getNodeId());
            if ("0".equals(ma.get("code").toString())) {
                Message m = new Message();
                m.setRecipients(nodeNewschedules.getOperatorUser());
                m.setText(ma.get("text").toString());
                m.setType("0");
                m.setPhone(nodeNewschedules.getOperatorPhone());
                m.setMsg(ma.get("msg").toString());
                m.setProjectName(np.getName());
                m.setResDept(nodeNewschedules.getResDept());
                m.setNodeId(nodeNewschedules.getSysId());
                ms.save(m);
            }
        }
    }

    /**
     * 审核不通过
     *
     * @param filter
     */
    public void initNoPassProject(NewProjectsFilter filter) {
        NewProjects newProjects = dao.getProjectById(filter.getSysId());
        newProjects.setStatus("5");
        dao.update(newProjects);
    }

    /**
     * 暂停项目
     *
     * @param filter
     */
    public void initStartProject(NewProjectsFilter filter) {
        NewProjects newProjects = dao.getProjectById(filter.getSysId());
        newProjects.setStatus("3");
        dao.update(newProjects);
    }

    /**
     * 暂停项目
     *
     * @param filter
     */
    public void initPauseProject(NewProjectsFilter filter) {
        NewProjects newProjects = dao.getProjectById(filter.getSysId());
        newProjects.setStatus("6");
        dao.update(newProjects);
    }


    public double getProjectSumPage(NewProjectsFilter filter) {
        double count = dao.getProjectSum(filter);
        double totalPage = Math.ceil(count / 10);//进一位
        return totalPage;
    }

    /**
     * 获取已完成或未开工的项目数
     *
     * @param projectType 项目类型，为null则不筛选
     * @return
     */
    public Map<String, Object> getStarOrNotWorkMap(String projectType) {
        Map<String, Object> map = new HashMap<>();
        //已完成
        int startWorkNum = dao.getStarOrNotWorkNum(true, projectType);
        //未开工
        int notStartWorkNum = dao.getStarOrNotWorkNum(false, projectType);
        //开工率
        String startWorkRate = NumberUtils.calculateRate(startWorkNum, startWorkNum + notStartWorkNum, 1);
        //未开工率
        String notStartWorkRate = NumberUtils.calculateRate(notStartWorkNum, startWorkNum + notStartWorkNum, 1);

        NewProjectsFilter filter = new NewProjectsFilter();
        filter.setProjectType(projectType);
        //重点项目
        List<NewProjects> projects = dao.getProjectInfo(filter);
        //计划投资
        double plannedInvestment = 0;
        for (NewProjects project : projects) {
            plannedInvestment += Double.parseDouble(StringUtils.isBlank(project.getMoney()) ? "0" : project.getMoney());
        }
        if ("2001".equals(projectType)) {
            map.put("title", "计划新开工项目");
        } else if ("2002".equals(projectType)) {
            map.put("title", "结转项目");
        }
        DecimalFormat decimalFormat = new DecimalFormat("###,###.00");
        //科学计数法调整
//        map.put("plannedInvestment", NumberUtils.doubleFormat(plannedInvestment, 2));
        map.put("plannedInvestment", kexuejishu(NumberUtils.doubleFormat(plannedInvestment, 2) + ""));
        map.put("startWorkNum", startWorkNum);
        map.put("notStartWorkNum", notStartWorkNum);
        map.put("allProjects", startWorkNum + notStartWorkNum);
        map.put("startWorkRate", startWorkRate);
        map.put("notStartWorkRate", notStartWorkRate);
        return map;
    }


    public Map<String, Object> getStarOrNotWorkMapByUser(String projectType, BnpUser user) {
        Map<String, Object> map = new HashMap<>();
        //已完成
        int startWorkNum = dao.getStarOrNotWorkNumByUser(true, projectType, user);
        //未开工
        int notStartWorkNum = dao.getStarOrNotWorkNumByUser(false, projectType, user);
        //开工率
        String startWorkRate = NumberUtils.calculateRate(startWorkNum, startWorkNum + notStartWorkNum, 1);
        //未开工率
        String notStartWorkRate = NumberUtils.calculateRate(notStartWorkNum, startWorkNum + notStartWorkNum, 1);

        NewProjectsFilter filter = new NewProjectsFilter();
        filter.setProjectType(projectType);

        if ("6".equals(user.getBranchType())) {
            //县分管领导
            filter.setResPhone(user.getPhone());
        }
        //重点项目
        List<NewProjects> projects = dao.getProjectInfo(filter);
        //计划投资
        double plannedInvestment = 0;
        for (NewProjects project : projects) {
            plannedInvestment += Double.parseDouble(StringUtils.isBlank(project.getMoney()) ? "0" : project.getMoney());
        }
        if ("2001".equals(projectType)) {
            map.put("title", "计划新开工项目");
        } else if ("2002".equals(projectType)) {
            map.put("title", "结转项目");
        }
        DecimalFormat decimalFormat = new DecimalFormat("###,###.00");
        //科学计数法调整
//        map.put("plannedInvestment", NumberUtils.doubleFormat(plannedInvestment, 2));
        map.put("plannedInvestment", kexuejishu(NumberUtils.doubleFormat(plannedInvestment, 2) + ""));
        map.put("startWorkNum", startWorkNum);
        map.put("notStartWorkNum", notStartWorkNum);
        map.put("allProjects", startWorkNum + notStartWorkNum);
        map.put("startWorkRate", startWorkRate);
        map.put("notStartWorkRate", notStartWorkRate);
        return map;
    }

    /**
     * 查询个行业数量和总项目数
     *
     * @return
     */
    public Map<String, Object> queryIndustryInfo() {
        List<NewProjectsFilter> industryList = dao.queryIndustryInfo();
        double count = dao.getProjectSum(null);
        for (NewProjectsFilter newProject : industryList) {
            Double a = (newProject.getNum().intValue()) / count * 100;
            newProject.setPage(Integer.parseInt(new java.text.DecimalFormat("0").format(a)));
            List<NewProjects> projects = null;
            projects = dao.getProjectInfo(newProject);
            //计划投资
            double plannedInvestment = 0;
            for (NewProjects project : projects) {
                plannedInvestment += Double.parseDouble(StringUtils.isBlank(project.getMoney()) ? "0" : project.getMoney());
            }
            newProject.setDoble(NumberUtils.doubleFormat(plannedInvestment, 2));
            //超前统计，逾期，正常
            newProject.setSchedleadingNum("0");
            newProject.setSchednormalNum(newProject.getNum().toString());
            newProject.setSchedoverdueNum("0");
            switch (newProject.getIndustryType()) {
                case "1001":
                    newProject.setIndustryType("旅游特色小镇项目");
                    newProject.setNatureType("1001");
                    break;
                case "1002":
                    newProject.setIndustryType("工业项目");
                    newProject.setNatureType("1002");
                    break;
                case "1003":
                    newProject.setIndustryType("交通");
                    newProject.setNatureType("1003");
                    break;
                case "1004":
                    newProject.setIndustryType("城镇基础设施");
                    newProject.setNatureType("1004");
                    break;
                case "1005":
                    newProject.setIndustryType("安置房项目");
                    newProject.setNatureType("1005");
                    break;
                case "1006":
                    newProject.setIndustryType("社会事业项目");
                    newProject.setNatureType("1006");
                    break;
                case "1007":
                    newProject.setIndustryType("商住项目");
                    newProject.setNatureType("1007");
                    break;
                case "1008":
                    newProject.setIndustryType("农林水利环保生态项目");
                    newProject.setNatureType("1008");
                    break;
                default:
                    break;
            }
        }
//        NewProjectsFilter filter = new NewProjectsFilter();
//        //重点项目
//        List<NewProjects> projects = null;
//        projects = dao.getProjectInfo(filter);
//        //计划投资
//        double plannedInvestment = 0;
//        for (NewProjects project : projects) {
//            plannedInvestment += Double.parseDouble(StringUtils.isBlank(project.getMoney()) ? "0" : project.getMoney());
//        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("count", count);
        map.put("industry", industryList);

        return map;
    }

    public List<NewProjectsFilter> queryScheduleInfo() {
        List<NewProjectsFilter> list = dao.queryScheduleInfo();
        for (NewProjectsFilter n : list) {
            n.setSchedleadingNum("0");
            n.setSchednormalNum(n.getNum().toString());
            n.setSchedoverdueNum("0");

            switch (n.getSchedCode()) {
                case "3001":
                    n.setType("前期项目");
                    break;
                case "3002":
                    n.setType("开工项目");
                    break;
                case "3003":
                    n.setType("在建提速");

                    break;
                case "3004":
                    n.setType("竣工项目");
                    break;
                default:
                    break;
            }
        }
        return list;
    }

    /**
     * 根据类型获取第一条项目ID
     *
     * @param projectType
     * @return
     */
    public String getFirstProjectIdByType(String projectType, String status) {
        return dao.getFirstProjectIdByType(projectType, status);
    }

    public List<NewProjects> getProjectInfo2(NewProjectsFilter filter) {
        return dao.getProjectInfo2(filter);
    }

    public List<NewProjects> getProjectInfo4(NewProjectsFilter filter) {
        return dao.getProjectInfo4(filter);
    }

    public List<NewProjects> getProjectInfoNoPage(NewProjectsFilter filter) {
        return dao.getProjectInfoNoPage(filter);
    }


    public List<NewProjects> getFinishProject() {
        return dao.getFinishProject();
    }

    public List<NewProjects> getProjectsInfo(NewProjectsFilter filter) {
        return dao.getProjectsInfo(filter);
    }

    public List<NewProjects> getProjectInfo3(NewProjectsFilter filter) {
        return dao.getProjectInfo3(filter);
    }

    public int getProjectsByNatureTypeDetail(String NatureTypeDetail) {
        return dao.getProjectsByNatureTypeDetail(NatureTypeDetail);
    }

    public Map<String, Object> updateProjectInfo(NewProjects oldPro, NewProjects newPro,
                                                 String ip, BnpUser user) throws NoSuchFieldException {
        String[] arrays = {
                "updUser",
                "updTime",
                "updDate",
                "createUser",
                "createTime",
                "createDate",
                "userId",
                "natureType",
                "natureTypeDetail",
                "status",
                "planBeginDate",
                "startTime",
                "groupCode",
                "groupName",
                "factFinishDate",
                "projectClassification",
                "position"};

        Map<String, List<Object>> map = CompareUtil.compareFields(oldPro, newPro, arrays);
        Iterator<Map.Entry<String, List<Object>>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, List<Object>> entry = entries.next();
            String key = entry.getKey();
            List<Object> value = entry.getValue();
            BeanSetGetUtil.setValue(oldPro,
                    oldPro.getClass(),
                    key,
                    NewProjects.class.getDeclaredField(key).getType(),
                    value.get(1));
        }
        Map<String, Object> result = new HashMap<>();
        //判断分管领导与手机号是否正确(分管领导)
        if (StringUtils.isNotBlank(oldPro.getResUser()) && StringUtils.isNotBlank(oldPro.getResPhone())) {
            BnpUser flag1 = bnpUserService.getBnpUserByPhoneAndName(oldPro.getResPhone(), oldPro.getResUser());
            if (ObjectUtils.isBlank(flag1)) {
                result.put("success", false);
                result.put("msg", "分管领导信息错误");
                return result;
            }
        }
        //判断联系人与手机号是否正确(联系人)
        BnpUser contacts = new BnpUser();
        BnpUser flag3 = new BnpUser();
        if (StringUtils.isNotBlank(oldPro.getContactName()) && StringUtils.isNotBlank(oldPro.getContactPhone())) {
            contacts = bnpUserService.getBnpUserByPhoneAndName(oldPro.getContactPhone(), oldPro.getContactName());
            if (ObjectUtils.isBlank(contacts)) {
                result.put("success", false);
                result.put("msg", "联系人信息错误");
                return result;
            }
        }
        //判断责任人与手机号是否正确(责任人)
        if (StringUtils.isNotBlank(oldPro.getOwnerUnitPerson()) && StringUtils.isNotBlank(oldPro.getOwnerUnitPersonPhone())) {
            flag3 = bnpUserService.getBnpUserByPhoneAndName(oldPro.getOwnerUnitPersonPhone(), oldPro.getOwnerUnitPerson());
            if (ObjectUtils.isBlank(flag3)) {
                result.put("success", false);
                result.put("msg", "责任人信息错误");
                return result;
            }
        }
        //更改业主经办人与责任人
        oldPro.setUserId(contacts.getSysId());
        NodeNewschedulesFilter nodeNewschedulesFilter = new NodeNewschedulesFilter();
        nodeNewschedulesFilter.setProjectId(oldPro.getSysId());
        List<NodeNewschedules> list = nodeNewschedulesDao.queryByFilter(nodeNewschedulesFilter);
        for (NodeNewschedules node : list) {
            if ("业主单位".contains(node.getResDept()) ||
                    "中介机构".contains(node.getResDept()) ||
                    "业主、中介机构".contains(node.getResDept())) {
                //经办人
                node.setOperatorUser(contacts.getName());
                node.setOperatorPhone(contacts.getPhone());
                //责任人
                node.setResUser(oldPro.getOwnerUnitPerson());
                node.setResUserPhone(oldPro.getOwnerUnitPersonPhone());
            }
        }
        nodeNewschedulesDao.batchUpdate(list);

        //更新经办人相关信息（督查表、绩效表、完成情况表、预警表）
        changeService.updateChangeOperatorUser(
                oldPro.getSysId(),
                oldPro.getContactName(),
                oldPro.getContactPhone(),
                contacts.getSysId()
        );
        //更新责任人相关信息（督查表、绩效表、完成情况表、预警表）
        changeService.updateChangeResUser(
                oldPro.getSysId(),
                oldPro.getOwnerUnitPerson(),
                oldPro.getOwnerUnitPersonPhone(),
                flag3.getSysId());
        update(oldPro, ip, user);
        result.put("success", true);
        result.put("msg", "保存成功");
        return result;
    }

    /**
     * 根据id获取项目
     *
     * @param ids
     * @return
     */
    public List<NewProjects> getProjects(List<String> ids) {
        List<NewProjects> list = new ArrayList<>();
        for (String id : ids) {
            NewProjects np = getById(id);
            list.add(np);
        }
        if (ObjectUtils.isBlank(ids)) {
            list = query();
        }
        return list;
    }


    //节点正常完成，绩效评分100.0
    public void updateFullMarkPoint(NodeNewschedules nodeNewschedules, NewProjects project) {

        SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
        taskFilter.setNodeSysId(nodeNewschedules.getSysId());
        List<SupervisionTask> supervisionTasks = supervisionTaskService.querySupervisionTaskByFilter(taskFilter);

        if (ObjectUtils.isBlank(supervisionTasks)) {
            String operatorUser = nodeNewschedules.getOperatorUser();
            String operatorPhone = nodeNewschedules.getOperatorPhone();
            BnpUser bnpUser1 = bnpUserService.getBnpUserByPhoneAndName(operatorPhone, operatorUser);
            if (ObjectUtils.isNotBlank(bnpUser1)) {
                GradePoint grade = new GradePoint();
                grade.setSoucre("100.0");
                grade.setTaskId("sch_" + nodeNewschedules.getSysId());//未进入督查做唯一标识
                if ("0".equals(bnpUser1.getBranchType())) {
                    grade.setCheckType("业主单位经办人");
                    grade.setCheckObjectId(bnpUser1.getSysId());
                    grade.setResDept(bnpUser1.getBranch());
                }
                if ("1".equals(bnpUser1.getBranchType())) {
                    grade.setCheckType("审批部门经办人");
                    grade.setCheckObjectId(bnpUser1.getSysId());
                    grade.setResDept(bnpUser1.getBranch());
                }
                grade.setTaskContent(project.getName() + nodeNewschedules.getNodeId()
                        + "《" + nodeNewschedules.getNodeName() + "》已正常完成");
                grade.setCheckObject(operatorUser);
                grade.setTaskName(project.getName() + nodeNewschedules.getNodeId()
                        + "《" + nodeNewschedules.getNodeName() + "》已正常完成");

                GradePointFilter filter = new GradePointFilter();
                filter.setTaskContent("sch_" + nodeNewschedules.getSysId());
                List<GradePoint> list = gradePointService.queryGradePoint(filter);
                if (ObjectUtils.isBlank(list)) {
                    gradePointService.save(grade);
                }
            }

            String resUser = nodeNewschedules.getResUser();
            String resUserPhone = nodeNewschedules.getResUserPhone();
            BnpUser bnpUser2 = bnpUserService.getBnpUserByPhoneAndName(resUserPhone, resUser);
            if (ObjectUtils.isNotBlank(bnpUser2)) {
                GradePoint grade = new GradePoint();
                grade.setSoucre("100.0");
                grade.setTaskId("sch_" + nodeNewschedules.getSysId());//未进入督查做唯一标识
                if ("0".equals(bnpUser2.getBranchType())) {
                    grade.setCheckType("业主单位责任人");
                    grade.setCheckObjectId(bnpUser2.getSysId());
                    grade.setResDept(bnpUser2.getBranch());
                }
                if ("1".equals(bnpUser2.getBranchType())) {
                    grade.setCheckType("审批部门责任人");
                    grade.setCheckObjectId(bnpUser2.getSysId());
                    grade.setResDept(bnpUser2.getBranch());
                }
                grade.setTaskContent(project.getName() + nodeNewschedules.getNodeId()
                        + "《" + nodeNewschedules.getNodeName() + "》已正常完成");
                grade.setCheckObject(resUser);
                grade.setTaskName(project.getName() + nodeNewschedules.getNodeId()
                        + "《" + nodeNewschedules.getNodeName() + "》已正常完成");

                GradePointFilter filter = new GradePointFilter();
                filter.setTaskContent("sch_" + nodeNewschedules.getSysId());
                List<GradePoint> list = gradePointService.queryGradePoint(filter);
                if (ObjectUtils.isBlank(list)) {
                    gradePointService.save(grade);
                }
            }
        }

    }

    public List<String> getResDpetInAllProject() {
        return dao.getResDpetInAllProject();
    }

    public Map<String, NodeNewschedules> dealWithNodesMapByType(List<NodeNewschedules> list, String mapType) {
        Map<String, NodeNewschedules> result = new HashMap<>();
        String val;
        switch (mapType) {
            case "close":
                val = "2";
                break;
            case "open":
                val = "1";
                break;
            default:
                val = "";
                break;
        }
        for (NodeNewschedules node : list) {
            //取大节点
            if ("1".equals(node.getType())) {
                if (StringUtil.isNotBlank(val)) {
                    if (val.equals(node.getState())) {
                        if (!result.containsKey(node.getNodeId())) {
                            result.put(node.getNodeId(), node);
                        }
                    }
                } else {
                    if (!result.containsKey(node.getNodeId())) {
                        result.put(node.getNodeId(), node);
                    }
                }
            }
        }
        return result;
    }

    public String zzc(String preNodeIds, Map<String, NodeNewschedules> closeMap) {
        String newPreNodeId = "";
        if (preNodeIds.contains(",")) {
            String[] preNodeIdArr = preNodeIds.split(",");
            for (String s : preNodeIdArr) {
                while (closeMap.containsKey(s) && !s.contains(",")) {
                    s = closeMap.get(s).getPreNodeId();
                    newPreNodeId = zzc(s, closeMap);
                }
                if (StringUtil.isNotBlank(newPreNodeId)) {
                    newPreNodeId = newPreNodeId + "," + s;
                } else {
                    newPreNodeId = s;
                }
            }
        } else {
            while (closeMap.containsKey(preNodeIds) && !preNodeIds.contains(",")) {
                preNodeIds = closeMap.get(preNodeIds).getPreNodeId();
                newPreNodeId = zzc(preNodeIds, closeMap);
            }
            if (StringUtil.isNotBlank(newPreNodeId)) {
                newPreNodeId = newPreNodeId + "," + preNodeIds;
            } else {
                newPreNodeId = preNodeIds;
            }
        }
        return newPreNodeId;
    }

    //批量更新节点清单的有问题的前置节点
    public void updateNodeProcess(List<String> sysIdList) {
        for (String sysId : sysIdList) {
            List<NodeNewschedules> startNodes = nodeNewschedulesDao.getFirstNode4(sysId);
            //获取所有节点
            List<NodeNewschedules> list = nodeNewschedulesDao.getNodeByProjectId(sysId);
            Map<String, NodeNewschedules> openMap = dealWithNodesMapByType(list, "open");
            Map<String, NodeNewschedules> closeMap = dealWithNodesMapByType(list, "close");
            updateStartNode(startNodes, closeMap, openMap);
            System.out.println(sysId);
        }
    }


    //更新开始节点（#）
    public void updateStartNode(List<NodeNewschedules> startNodes,
                                Map<String, NodeNewschedules> closeMap,
                                Map<String, NodeNewschedules> openMap) {
        for (NodeNewschedules startNode : startNodes) {
            String newPreNodeId = "";
            String preNodeIds = startNode.getPreNodeId();
            if (preNodeIds.contains(",")) {
                String[] preNodeIdArr = preNodeIds.split(",");
                for (String s : preNodeIdArr) {
                    newPreNodeId = zzc(s, closeMap);
                }
            } else {
                newPreNodeId = zzc(preNodeIds, closeMap);
                if (StringUtil.isNotBlank(newPreNodeId)) {
                    newPreNodeId = newPreNodeId + "," + preNodeIds;
                } else {
                    newPreNodeId = preNodeIds;
                }
            }
            String preNodeId = "";
            String[] pNodeArr_old = newPreNodeId.split(",");
            String[] pNodeArr = removalRepeatArr(pNodeArr_old);
            for (String p : pNodeArr) {
                if (openMap.containsKey(p)) {
                    if (StringUtil.isNotBlank(preNodeId)) {
                        preNodeId = preNodeId + "," + p;
                    } else {
                        preNodeId = p;
                    }
                }
            }
            if (StringUtil.isBlank(preNodeId)) {
                preNodeId = "#";
            }
            startNode.setPreNodeId(preNodeId);
        }
        nodeNewschedulesDao.batchUpdate(startNodes);
    }


    /**
     * 开工时间
     *
     * @return
     */
    public Map<String, Object> queryStartSchedule() {
        //查询计划开工时间
        List<PlanStartScheduleDto> result1 = nodeNewschedulesDao.queryPlanStartSchedule();
        List<String> dataTimeList1 = new ArrayList<>();
        List<Integer> countList1 = new ArrayList<>();
        Map<String, Integer> planStartMap = new HashMap<>();
        for (PlanStartScheduleDto schedule : result1) {
            String dataTime = schedule.getDataTime();
            Integer count = Integer.parseInt(schedule.getCount().toString());
            if (StringUtil.isBlank(dataTime)) {
                continue;
            }
            planStartMap.put(dataTime, count);
            dataTimeList1.add(dataTime);
            countList1.add(count);
        }

        //查询实际开工时间
        List<PlanStartScheduleDto> result2 = nodeNewschedulesDao.queryFactStartSchedule();
        List<String> dataTimeList2 = new ArrayList<>();
        List<Integer> countList2 = new ArrayList<>();
        Map<String, Integer> factStartMap = new HashMap<>();
        for (PlanStartScheduleDto schedule : result2) {
            String dataTime = schedule.getDataTime();
            Integer count = Integer.parseInt(schedule.getCount().toString());
            if (StringUtil.isBlank(dataTime)) {
                continue;
            }
            factStartMap.put(dataTime, count);
            dataTimeList2.add(dataTime);
            countList2.add(count);
        }
        //实际开工的最后时间
        String lastDataTime = dataTimeList2.get(dataTimeList2.size() - 1);
        //实际开工数量
        int factStartCount = 0;
        for (Integer i : countList2) {
            factStartCount = factStartCount + i;
        }
        //求无重复并集
        dataTimeList1.removeAll(dataTimeList2);
        dataTimeList1.addAll(dataTimeList2);

        //时间排序
        Collections.sort(dataTimeList1, new Comparator<String>() {
            @Override
            public int compare(String t1, String t2) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy.MM");
                Date d1 = null, d2 = null;
                try {
                    d1 = format.parse(t1);
                    d2 = format.parse(t2);
                } catch (ParseException e) {
                    // 解析出错，则不进行排序
                    e.printStackTrace();
                }
                if (d1.before(d2)) {
                    return -1;
                } else {
                    return 1;
                }
            }
        });

        List<Integer> planStartList = new ArrayList<>();
        List<Integer> factStartList = new ArrayList<>();
        for (String s : dataTimeList1) {
            if (planStartMap.containsKey(s)) {
                planStartList.add(planStartMap.get(s));
            } else {
                planStartList.add(0);
            }

            if (factStartMap.containsKey(s)) {
                factStartList.add(factStartMap.get(s));
            } else {
                factStartList.add(0);
            }
        }
        Map<String, Object> scheduleResult = new HashMap<>();
        scheduleResult.put("timeList1", dataTimeList1);
        scheduleResult.put("planStartList", planStartList);
        scheduleResult.put("factStartList", factStartList);
        return scheduleResult;
    }

    /**
     * 根据时间查询实际开工时间跟计划开工时间的项目
     * 如项目未完成则列出剩余节点数
     *
     * @return
     */
    public List<Map<String, Object>> queryStartScheduleByDataTime(NewProjectsFilter filter) {
        List<NewProjects> list = dao.queryStartScheduleByDataTime(filter);
        List<Map<String, Object>> resList = new ArrayList<>();
        for (NewProjects projects : list) {
            Map<String, Object> map = new HashMap<>();
            String status = projects.getStatus();
            if ("4".equals(status)) {
                //剩余节点数
                map.put("surplusNodes", 0);
                map.put("surplusNodesList", new ArrayList<>());
                map.put("status", "已开工");
                map.put("planStartTime", projects.getStartTime());
                map.put("factStartTime", projects.getFactFinishDate());
                map.put("projectName", projects.getName());
                map.put("projectId", projects.getSysId());
            } else {
                //查询项目的剩余节点数

                NewProjectsFilter newProjectsFilter = new NewProjectsFilter();
                newProjectsFilter.setSysId(projects.getSysId());
                List<NodeNewschedules> surplusNodesList =
                        nodeNewschedulesDao.querySurplusNodesListByProjectId(newProjectsFilter);
                map.put("surplusNodes", surplusNodesList.size());
                map.put("surplusNodesList", surplusNodesList);
                map.put("status", "未开工");
                map.put("planStartTime", projects.getStartTime());
                map.put("factStartTime", projects.getFactFinishDate());
                map.put("projectName", projects.getName());
                map.put("projectId", projects.getSysId());
            }
            resList.add(map);
        }
        return resList;
    }
}
